﻿using DomainEventDemo.Plans.IntegrationEvents;
using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EventBus.Distributed;

namespace DomainEventDemo.Plans
{
    public class PlanAppService : ApplicationService, IPlanAppService
    {
        private readonly IRepository<Plan, Guid> _planRepository;
        private readonly IDistributedEventBus _distributedEventBus;

        public PlanAppService(IRepository<Plan, Guid> planRepository, IDistributedEventBus distributedEventBus)
        {
            _planRepository = planRepository;
            _distributedEventBus = distributedEventBus;
        }

        public async Task<string> CreateAsync(string name)
        {
            var plan = new Plan(name);
            await _planRepository.InsertAsync(plan);

            await _distributedEventBus.PublishAsync(new PlanCreatedIntegrationEvent()
            {
                Id = plan.Id
            });

            Console.WriteLine($"计划已创建.{DateTime.Now}");

            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                Console.WriteLine($"计划已创建，后续步骤执行中.{DateTime.Now}");
            }

            Console.WriteLine($"触发异常.{DateTime.Now}");
            throw new Exception("error");

            return name;
        }
    }
}
